<template>
  <el-dialog
    v-loading.body="menuLoading"
    :visible.sync="menuVisible"
    title="角色菜单管理"
    element-loading-text="玩命加载中"
  >
    <el-tree
      ref="tree"
      :data="menuData"
      :default-expanded-keys="expandedKeys"
      :default-checked-keys="checkedKeys"
      :props="defaultProps"
      show-checkbox
      node-key="resourceNo"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="menuVisible = false">取 消</el-button>
      <el-button :loading="formMenuSubmiting" type="primary" @click="commitMenuForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      roleId: null,
      // 菜单表单
      menuLoading: false,
      menuVisible: false,
      formMenuSubmiting: false,
      // 菜单数据
      roleCode: "",
      menuData: [],
      expandedKeys: [],
      checkedKeys: [],
      defaultProps: {
        children: "children",
        label: "resourceName"
      }
    };
  },
  methods: {
    _findNewArr(arrs) {
      let arr = arrs
      arr.forEach((v, i) => {
        v["label"] = v.resourceName
        if (v.children.length) {
          this._findNewArr(v.children)
        } else {
          return true
        }
      })
      return arr
    },
    filterResourceNo(data, newarr) {
      const arr = newarr || []
      data.forEach(v => {
        if (v.checked) {
          arr.push(v.resourceNo)
        }
        if (v.children.length) {
          this.filterResourceNo(v.children, newarr)
        }
      })
      return arr
    },
    getRoleMenu(code) {
      let arr = []
      this.menuVisible = true;
      this.menuLoading = true;
      this.roleCode = code
      this.$api.fenxiao.role
        .listTreeBySourceCode(code)
        .then(response => {
          this.menuData = response.data; 
          arr = this.filterResourceNo(response.data)
          this.checkedKeys = arr
          this.menuLoading = false;
        })
        .catch(error => {
          this.menuLoading = false;
          console.log(error);
        });
    },
    commitMenuForm() {
      this.formMenuSubmiting = true
      const keys = this.$refs.tree.getCheckedKeys()
      this.$api.fenxiao.menu
        .saveMenu({
          data: {
            resourceNoLists: keys,
            sourceCode: this.roleCode,
            sourceTypeEnum: "ROLE"
          }
        })
        .then(response => {
          this.formMenuSubmiting = false;
          this.menuVisible = false;
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            duration: 1500
          });
        })
        .catch(error => {
          this.formMenuSubmiting = false;
          this.$notify({
            title: "错误",
            message: error,
            type: "error",
            duration: 3000
          });
          console.log(error);
        });
    }
  }
};
</script>